from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required
from ..models.user import User

bp = Blueprint('auth', __name__)

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        print(f"Login attempt - username: {username}")  # 调试信息
        
        user = User.find_by_username(username)
        if user:
            print(f"User found: {user.id}")  # 调试信息
            if user.check_password(password):
                print("Password correct")  # 调试信息
                login_user(user)
                return redirect(url_for('main.index'))
            else:
                print("Password incorrect")  # 调试信息
        else:
            print("User not found")  # 调试信息
        
        flash('用户名或密码错误')
    
    return render_template('auth/login.html')

@bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))

@bp.route('/profile')
@login_required
def profile():
    return render_template('auth/profile.html') 